/**
 * 微应用性能监控工具
 */

interface AppPerformanceRecord {
  name: string;
  startTime: number;
  loadTime?: number;
  mountTime?: number;
  unmountTime?: number;
  duration?: number;
}

const performanceRecords: Record<string, AppPerformanceRecord> = {};

/**
 * 记录微应用加载开始时间
 * @param appName 微应用名称
 */
export function recordAppLoadStart(appName: string): void {
  performanceRecords[appName] = {
    name: appName,
    startTime: performance.now()
  };
  console.log(`[Performance] App ${appName} load started`);
}

/**
 * 记录微应用加载完成时间
 * @param appName 微应用名称
 */
export function recordAppLoadEnd(appName: string): void {
  const record = performanceRecords[appName];
  if (record) {
    record.loadTime = performance.now();
    console.log(`[Performance] App ${appName} loaded in ${record.loadTime - record.startTime}ms`);
  }
}

/**
 * 记录微应用挂载完成时间
 * @param appName 微应用名称
 */
export function recordAppMountEnd(appName: string): void {
  const record = performanceRecords[appName];
  if (record) {
    record.mountTime = performance.now();
    console.log(`[Performance] App ${appName} mounted in ${record.mountTime - record.startTime}ms`);
  }
}

/**
 * 记录微应用卸载完成时间
 * @param appName 微应用名称
 */
export function recordAppUnmountEnd(appName: string): void {
  const record = performanceRecords[appName];
  if (record) {
    record.unmountTime = performance.now();
    record.duration = record.unmountTime - record.startTime;
    console.log(`[Performance] App ${appName} unmounted, total duration ${record.duration}ms`);
    // 可以将性能数据上报到监控系统
    reportPerformanceData(record);
  }
}

/**
 * 上报性能数据
 * @param record 性能记录
 */
function reportPerformanceData(record: AppPerformanceRecord): void {
  // 这里可以实现将性能数据上报到监控系统的逻辑
  // 例如：通过API发送到后端或使用第三方监控服务
  if (process.env.NODE_ENV === 'production') {
    // 在生产环境上报数据
    console.log(`[Performance] Reporting data for ${record.name}`, record);
    // 实际项目中取消下面的注释并实现上报逻辑
    // fetch('/api/performance', {
    //   method: 'POST',
    //   headers: { 'Content-Type': 'application/json' },
    //   body: JSON.stringify(record)
    // });
  }
}

/**
 * 获取所有微应用的性能记录
 * @returns 性能记录对象
 */
export function getPerformanceRecords(): Record<string, AppPerformanceRecord> {
  return { ...performanceRecords };
}